package com.me.learnspring.service;

import com.me.learnspring.model.Category;
import com.me.learnspring.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {
	@Autowired
	private CategoryRepository crepo;
	
	public Category saveCategory(String name) {
		return crepo.save(Category.builder().name(name).build());
	}
	
	public Category saveCategory(Category category){
		return crepo.save(category);
	}
	
	public List<Category> findAll() {
		return crepo.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
	}
	
	public Category findOne(String name) {
		// var matcher = ExampleMatcher.matching().withIgnoreCase("name").withIgnoreNullValues();
		//
		// var example = Example.of(Category.builder().name(name).build(), matcher);
		//
		// Optional<Category> category = crepo.findOne(example);
		//
		// return category.orElse(null);
		return crepo.findByName(name).orElse(null);
	}
	
	public Category update(long id, String name) {
		Optional<Category> category = crepo.findById(id);
		if (category.isPresent()) {
			Category oldCategory = category.get();
			oldCategory.setName(name);
			return crepo.saveAndFlush(oldCategory);
		}
		
		return null;
	}
	
	public boolean delete(long id) {
		try {
			crepo.deleteById(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public Category findById(Long id) {
		return crepo.findById(id).orElse(null);
	}
}
